<template>
    <div>
        <el-form class="form-box" ref="formRef" :model="form" label-width="auto" size="large">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="收款金额：" prop="salaAmt">
                        <div class="salaAmt">{{ unpay }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="收取金额：" prop="payAmt">
                        <el-input v-model="form.payAmt" placeholder="请输入金额" @focus="focusForm('payAmt')" @blur="blurForm"
                            clearable oninput="value=value.replace(/[^0-9.]/g,'')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="付款条码：" prop="authCode">
                        <el-input v-model="form.authCode" placeholder="点击扫码" @focus="focusForm('authCode')" @blur="blurForm"
                            clearable @change="changeAuthCode()" @keyup.enter.native="emit('keyupEnter')" />
                        <img class="qrcode-img" src="https://jtmc.oss-cn-hangzhou.aliyuncs.com/pc/images/vip/qrcode.png"
                            alt="">
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <div class="tip">说明 ：点客户付款码条码，手动输入条码数值，同样可以扣款</div>

                </el-col>
                <el-col :span="24">
                    <el-form-item label="支付结果：" prop="finalAmt">
                        <div class="finish-box">
                            <div class="finish-type-success" v-if="finishType == '成功'">
                                {{ finishType }}
                            </div>
                            <div class="finish-type-others" v-else>
                                {{ finishType }}
                            </div>
                            <div class="countdown" v-show="seconds < 31 && seconds > -1">（{{ seconds }}s）</div>
                            <el-button v-show="seconds > 30 && finishType == '支付中...'" class="select-pay-btn"
                                @click="searchPayType">网上支付查询</el-button>
                        </div>

                    </el-form-item>
                </el-col>
                <el-col v-show="false" :span="24" class="qrcode-box-left">
                    <div class="title">支付成功返回码：</div>
                    <div>
                        <el-input v-model="form.code" disabled />
                    </div>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script setup >
import ls from '@/lib/ls'
import { formatDecimal } from '@/utils/chenhao'
import Api from '@/api'
import { getLocalIPv4 } from "@/utils/getip.js";
import useConfigStore from '@/store/config'
const configStore = useConfigStore()
// 接收父组件参数 props
const props = defineProps({
    tableInfo: {
        type: Object,
        required: false,
    },
    selectWares: {
        type: Array,
        required: false,
    },
    received: {
        type: String,
        required: false,
    },
    form: {
        type: Object,
        required: false,
    },
    price: {
        type: String,
        required: false,
    },
    unpay: {
        type: String,
        required: false,
    },
    payData: {
        type: Array,
        required: false,
    },
    saleData: {
        type: Array,
        required: false,
    },
    details: {
        type: Array,
        required: false,
    },
})
const tableInfo = toRef(props, 'tableInfo')
const selectWares = toRef(props, 'selectWares')
const received = toRef(props, 'received')
const price = toRef(props, 'price')
const unpay = toRef(props, 'unpay')
const form = toRef(props, 'form')
const payData = toRef(props, 'payData')
const saleData = toRef(props, 'saleData')
const details = toRef(props, 'details')

const emit = defineEmits(['focusForm'])


const router = useRouter()
const todo = router.currentRoute.value.query.todo
const cardNo = router.currentRoute.value.query.cardNo


// 数字键盘
const focusForm = (str) => {
    // keyboard.value = true
    emit('focusForm', str)
}
const blurForm = (params) => {
    // keyboard.value = false
}
// 改变付款条码
const changeAuthCode = (params) => {
    finishType.value = ''
}
// 倒计时
const seconds = ref(31);
let interval = reactive({ re: {} })
const countdown = () => {
    seconds.value = 30;
    interval = setInterval(() => {
        if (seconds.value === 0) {
            console.log('倒计时结束 :>> ');
            clearIv(interval);
        } else {
            seconds.value -= 1;
            if (seconds.value % 5 === 0 && finishType.value == '支付中...') {
                searchPayType()
            }
        }
    }, 1000);
    return interval;
};
const clearIv = (interval) => {
    seconds.value = 31;
    clearInterval(interval);
}

// 父组件小键盘点击确定
let finishType = ref('')
const handleKeyboardConfirm = (params) => {
    if (Number(form.value.payAmt) > Number(unpay.value)) return ElNotification({
        title: '提示',
        message: '收取金额不能大于收款金额',
        type: 'warning',
    })
    if (finishType.value == '支付中...') return ElNotification({
        title: '提示',
        message: '正在支付中，请勿重复确认',
        type: 'warning',
    })
    if (!form.value.payAmt) return ElNotification({
        title: '提示',
        message: '请输入收取金额',
        type: 'warning',
    })
    if (!form.value.authCode) return ElNotification({
        title: '提示',
        message: '请扫描付款码',
        type: 'warning',
    })
    form.value.payCode = ''
    configStore.payFlag = true // 支付开关
    let data = {
        authCode: form.value.authCode,
        fee: form.value.payAmt,
        payType: '1',
    }
    // 调用微信和支付宝支付接口
    finishType.value = "支付中..."
    console.log('调用支付接口前的 data :>> ', data);
    clearIv(interval)
    interval = countdown();
    // return
    Api.Common.PcObjProcess.Do({ "functionName": "MenberCodePay", "orgCode": "0004", "contentData": data }).then(res => {
        configStore.ispaying.id ++
        console.log('调用微信和支付宝支付接口res :>> ', res);
        if (res.TradeState == "Success") {
            finishType.value = "成功"
            clearIv(interval)
            form.value.payCode = res.OutTradeNo
            confirm()
        }
        else if (res.TradeState == "Fail") {
            form.value.payCode = res.OutTradeNo
        }
    }).catch(err => {
        configStore.ispaying.id ++
        console.log('err :>> ', err);
        // if (err.ApiError.Message == '101 每个二维码仅限使用一次，请刷新再试') return
        finishType.value = "支付失败"
        clearIv(interval)
    });
}

// 网上支付查询
let flag = ref(0)
const searchPayType = (params) => {
    if(!form.value.payCode) return
    flag.value += 1
    let data = {
        "OutTradeNo": form.value.payCode,
        "payType": "1"
    }
    console.log('调用网上支付查询前的 data :>> ', data, form.value);
    Api.Common.PcObjProcess.Do({ "functionName": "MenberCodePayQuery", "orgCode": "0004", "contentData": data }).then(res => {
        console.log('微信支付查询 :>> ', res);
        if (res.result == "支付成功") {
            // ElNotification({
            //     title: '成功',
            //     message: '支付成功',
            //     type: 'success',
            // })
            clearIv(interval);
            finishType.value = "成功"
            confirm()
        }
        else if (res.result == "等待支付") {
            // ElNotification({
            //     title: '提示',
            //     message: '支付中...',
            //     type: 'warning',
            // })
        }
        else if (res.result == "取消支付") {
            finishType.value = "取消支付"
        }
    }).catch(err => {
        console.log('err :>> ', err);
        clearIv(interval);
        finishType.value = "支付失败"
    });
}
const confirm = () => {
    // 换菜
    if (todo == 'orderChange') {
        orderChange()
    }
    // 会员升级
    else if (todo == 'vipUpgrade') {
        vipUpgrade()
    }
    // 挂账还款
    else if (todo == 'mountPay') {
        mountPay()
    }

}

// 换菜支付
const orderChange = (params) => {
    // 处理勾选的商品
    let detailList = []
    if (details.value.length > 0) {
        console.log('1 :>> ', 1);
        detailList = details.value
    } else {
        console.log('2 :>> ', 2);
         console.log(selectWares.value);
        let toolArr = []
        selectWares.value.forEach(item=>{
            toolArr.push(item)
            if (item.subGoods && item.subGoods.length > 0) {
                toolArr.push(...item.subGoods)
            }
        })
   
        console.log(toolArr);
        
        detailList = toolArr.map(item => {
            return item.itemCode
        })
    }
    const obj = {
        zffs: form.value.actionType,
        skje: formatDecimal(form.value.payAmt),
        consumeCode: form.value.consumeCode,
        payType: '002',
        totalAmt: unpay.value,
        payAmt: form.value.payAmt,
        tradeNo: form.value.payCode,
        detailList,
    }
    const data = {
        payType: '002',
        tradeNo: form.value.payCode,
        consumeCode: tableInfo.value.consumeCode,
        roomCode: tableInfo.value.roomCode,
        payBatchCode: tableInfo.value.payBatchCode,
        orderAmt: price.value,
        realPayAmt: form.value.payAmt,
        detailList: detailList.join(','),
        payList: [obj],
        serviceAmt: saleData.value
    }
    Api.Common.PcObjProcess.Do({ "functionName": "OrderPay", "orgCode": "0004", "contentData": data })
        .then(res => {
            console.log('买单确认res :>> ', res);
            obj.itemCode = res.itemCode
            obj.payBatchCode = res.payBatchCode
            tableInfo.value.payBatchCode = res.payBatchCode
            payData.value.push(obj)
            const ls_orderChange = ls.get('orderChange')
            if (ls_orderChange) {
                ls_orderChange.payData = payData.value
                ls.set('orderChange', ls_orderChange)
            }
            form.value.payAmt = ''
            form.value.authCode = ''
        })
}

// 会员升级
const vipUpgrade = (params) => {
    const obj = {
        zffs: form.value.actionType,
        skje: formatDecimal(form.value.payAmt),
        payType: '002',
        totalAmt: unpay.value,
        payAmt: form.value.payAmt,
        tradeNo: form.value.payCode,
    }
    const data = {
        payType: '002',
        tee: form.value.payAmt,
        tradeNo: form.value.payCode,
        cardNo: cardNo,
    }
    // console.log('会员升级支付确认 data :>> ', data);
    Api.Common.PcObjProcess.Do({ "functionName": "MemberUpPay", "contentData": data })
        .then(res => {
            console.log('会员升级支付确认 res :>> ', res);
            obj.itemCode = res.itemCode
            payData.value.push(obj)
            form.value.payAmt = ''
            form.value.authCode = ''
        })
}

//获取ip地址
const ip = ref("");
getLocalIPv4()
    .then((ipAddress) => {
        // 在这里处理获取到的 IP 地址
        ip.value = ipAddress;
        console.log("IP 地址:", ip.value);
    })
    .catch((error) => {
        console.error("发生错误:", error);
        // 在这里处理错误情况
    });

// 挂账还款
const mountPay = (params) => {
    // console.log('挂账还款支付确认 data :>> ', router.currentRoute.value.query);
    const { consumeCode, payBatchCode, roomCode, payItemCode } = router.currentRoute.value.query
    const obj = {
        zffs: form.value.actionType,
        skje: formatDecimal(form.value.payAmt),
        consumeCode,
        payType: '002',
        totalAmt: unpay.value,
        payAmt: form.value.payAmt,
        tradeNo: form.value.payCode,
    }
    const data = {
        payType: '002',
        tradeNo: form.value.payCode,
        consumeCode,
        roomCode,
        payBatchCode,
        payItemCode,
        payAmt: form.value.payAmt,
        // payList: [obj],
        serviceAmt: saleData.value,
        ip:ip.value
    }
    // return
    console.log('挂账还款接口调用前的 data :>> ', data);
    Api.Common.PcObjProcess.Do({ "functionName": "MountPay", "contentData": data })
        .then(res => {
            console.log('挂账还款 res :>> ', res);
            obj.itemCode = res.itemCode
            payData.value.push(obj)
            form.value.payAmt = ''
            form.value.authCode = ''
        })
}

// 暴露方法给父组件
defineExpose({ handleKeyboardConfirm })
</script>

<style scoped lang="scss">
.form-box {
    margin-top: 20px;

    ::v-deep {
        .el-input__wrapper {
            background: #F9F9F9;
            border-radius: 8px;
            border: 0;
            font-size: 16px;
            color: #999999;
        }
    }

    .salaAmt {
        font-weight: 400;
        font-size: 16px;
        color: #FF3333;
    }

}

.qrcode-img {
    width: 24px;
    height: 24px;
    position: absolute;
    right: 10px;
    cursor: pointer;
}

.tip {
    font-size: 13px;
    color: #999999;
    margin-bottom: 10px;
}

.finish-box {
    // position: reactive;
    display: flex;
    // align-items: center;
    size: 16px;
    color: #FF3333;
    height: 50px;
    // font-size: 16px;

    .finish-type-success {
        ::v-deep {
            .el-input__inner {
                font-size: 16px;
                color: #67C23A;

            }
        }
    }

    .finish-type-others {
        ::v-deep {
            .el-input__inner {
                font-size: 16px;
                color: #FF3333;

            }
        }
    }

    .select-pay-btn {
        width: 120px;
        height: 40px;
        border-radius: 8px;
        border: 1px solid #E6E6E6;
        font-size: 16px;
        color: #FF6A00;
        margin-left: 20px;
    }
}
</style>
